# -*- coding: utf-8 -*-
"""
@Time ： 2022/12/13 9:53
@Author ： ZhengYunYi
@File ：Selenium1.py
@IDE ：PyCharm

"""
from selenium import webdriver
from selenium.webdriver.common.by import By  # 查找元素
from selenium.webdriver.support.ui import WebDriverWait  # 等待元素出现

option = webdriver.ChromeOptions()
option.add_argument("--headless")
# 无头浏览器需要添加user-agent来隐藏特征
option.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                    'Chrome/94.0.4606.71 Safari/537.36')
driver = webdriver.Chrome(options=option)
driver.implicitly_wait(1)
with open('Files/stealth.min.js') as f:
    js = f.read()
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": js
})
driver.get('https://bot.sannysoft.com/')
driver.save_screenshot('hidden_features.png')


def FindElement():
    """
    获取单个节点的方法
    find_element(Type, Str)
    Type:By.ID,By.NAME,By.XPATH,By.CSS_SELECTOR

    driver.find_element(By.XPATH,'XPATH')
    # 绝对路径（层级关系）定位
    driver.find_element_by_xpath("/html/body/div/div/div/div[2]/div/div/input[1]")
    # 利用元素属性定位
    driver.find_element_by_xpath("//*[@id='toolbar-search-input']"))
    # 层级+元素属性定位
    driver.find_element_by_xpath("//div[@id='csdn-toolbar']/div/div/div[2]/div/div/input[1]")
    # 逻辑运算符定位
    driver.find_element_by_xpath("//*[@id='toolbar-search-input' and @autocomplete='off']")

    driver.find_element(By.CSS_SELECTOR,'CSS_SELECTOR')
    .class	.toolbar-search-container	选择 class = 'toolbar-search-container' 的所有元素
    #id	    #toolbar-search-input	    选择 id = 'toolbar-search-input' 的元素
    *	    *	                        选择所有元素
    element	    input	                选择所有 input元素
    element>element	    div>input	    选择父元素为 div的所有input元素
    element+element	    div+input	    选择同一级中在 div之后的所有 input元素
    [attribute=value]	type='text'	    选择 type = 'text' 的所有元素

    driver.find_element(By.LINK_TEXT,'LINK_TEXT')
    <div class="practice-box" data-v-04f46969="">加入！每日一练</div>
    匹配'加入！每日一练'这个div
    driver.find_element(By.PARTIAL_LINK_TEXT,'PARTIAL_LINK_TEXT')
    用法同上，输入部分文字即可匹配

    driver.find_element(By.CLASS_NAME,'CLASS_NAME')
    driver.find_element(By.ID,'ID')
    driver.find_element(By.NAME,'NAME')
    driver.find_element(By.TAG_NAME,'TAG_NAME')
    """
    driver.get('https://www.taobao.com')
    a = driver.find_element(By.ID, 'q')
    b = driver.find_element(By.NAME, 'q')
    c = driver.find_element(By.XPATH, '//*[@id="q"]')
    d = driver.find_element(By.CSS_SELECTOR, '#q')
    print(a, b, c, d)
    print(a == b == c == d)
    pass


def FindElements():
    """
    获取多个节点的方法
    用法同单个，返回列表
    """
    driver.get('https://www.taobao.com')
    a = driver.find_elements(By.CSS_SELECTOR, '.service-bd li')
    print(a)
    pass


def WaitElement():
    """
    等待节点出现
    WebDriverWait(driver, timeout=3).until(lambda d: d.find_element(By.ID, 'q'))
    driver就是浏览器驱动，timeout就是等待的时长，until后是判断元素是否出现的,返回目标
    """
    driver.get('https://www.taobao.com')
    a = WebDriverWait(driver, timeout=3).until(lambda d: d.find_element(By.ID, 'q'))
    b = driver.find_element(By.NAME, 'q')
    print(a == b)
    pass


def ChangeFrame():
    driver.get('https://www.taobao.com')
    # 1.通过id定位
    driver.switch_to.frame('CSDN_info')
    # 2.通过name定位
    driver.switch_to.frame('Dream丶Killer')
    # 通过xpath定位
    iframe_label = driver.find_element(By.XPATH, '/html/body/iframe')
    driver.switch_to.frame(iframe_label)
    pass


def Cookie():
    driver.get("https://blog.csdn.net/")

    # 输出所有cookie信息
    print(driver.get_cookies())

    cookie_dict = {
        'domain': '.csdn.net',
        'expiry': 1664765502,
        'httpOnly': False,
        'name': 'test',
        'path': '/',
        'secure': True,
        'value': 'null'}

    # 添加cookie
    driver.add_cookie(cookie_dict)
    # 显示 name = 'test' 的cookie信息
    print(driver.get_cookie('test'))
    # 删除 name = 'test' 的cookie信息
    driver.delete_cookie('test')
    # 删除当前会话中的所有cookie
    driver.delete_all_cookies()
    pass


def Hidebot():
    option = webdriver.ChromeOptions()
    option.add_argument("--headless")
    # 无头浏览器需要添加user-agent来隐藏特征
    option.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                        'Chrome/94.0.4606.71 Safari/537.36')

    driver = webdriver.Chrome(options=option)
    driver.implicitly_wait(2)

    with open('Files/stealth.min.js') as f:
        js = f.read()

    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": js
    })

    driver.get('https://bot.sannysoft.com/')
    driver.save_screenshot('hidden_features.png')
    pass


if __name__ == '__main__':
    """
    # 刷新页面driver.refresh()
    # 在原页面打开driver.get('https://blog.csdn.net/qq_43965708')
    # 新标签中打开js = "window.open('https://blog.csdn.net/qq_43965708')"
        driver.execute_script(js)
    # 前进driver.forward()    后退driver.back()
    #   获取打开的多个窗口句柄windows = driver.window_handles
        切换到当前最新打开的窗口driver.switch_to.window(windows[-1])
    #send_keys()	模拟输入指定内容
    #clear()	清除文本内容
    #is_displayed()	判断该元素是否可见
    #get_attribute()	获取标签属性值
    #size	返回元素的尺寸
    #text	返回元素文本
    """
    # FindElements()
    # ChangeFrame()
    # Cookie()
    # driver.get("https://bot.sannysoft.com/")
    # driver.close()
    pass
